/*
    File:       TCPSocket.h

    Contains:   TCP socket object
                    
    
    
    
*/

#ifndef __TCPSOCKET_H__
#define __TCPSOCKET_H__

#include <stdio.h>
#include <stdlib.h>
#ifndef __Win32__
#include <sys/types.h>
#include <sys/socket.h>
#endif

#include <string>

#include "OSHeaders.h"
#include "Socket.h"

#define ERR_SOCKET_FULL	30000

class TCPSocket : public Socket
{
    public:

	//TCPSocket takes an optional task object which will get notified when
	//certain events happen on this socket. Those events are:
	//
	//S_DATA:               Data is currently available on the socket.
	//S_CONNECTIONCLOSING:  Client is closing the connection. No longer necessary
	//                      to call Close or Disconnect, Snd & Rcv will fail.
	TCPSocket() {}
	
	virtual ~TCPSocket() {}
	
	Bool		Set(int inSocket, const struct sockaddr_in* remoteaddr = NULL);
		
	OS_Error	Open() { return Socket::Open(SOCK_STREAM); }
	
	// Connect. Attempts to connect to the specified remote host. If this
	// is a non-blocking socket, this function may return EINPROGRESS, in which
	// case caller must wait for either an EV_RE or an EV_WR. You may call
	// CheckAsyncConnect at any time, which will return OS_NoErr if the connect
	// has completed, EINPROGRESS if it is still in progress, or an appropriate error
	// if the connect failed.
	OS_Error	Connect(UInt32 inRemoteAddr, UInt16 inRemotePort, UInt32 uTimeout = 0 );
	//OS_Error  CheckAsyncConnect();
	
	// Basically a copy constructor for this object, also NULLs out the data
	// in tcpSocket.
	OS_Error	Listen(UInt32 inAcceptCount);
	Int32		Accept(TCPSocket *v_Socket=NULL);
	
	Bool		SnarfSocket( TCPSocket & tcpSocket );
	
	//ACCESSORS:
	//Returns NULL if not currently available.
	
	UInt32		GetRemoteAddr() { return ntohl(fRemoteAddr.sin_addr.s_addr); }
	UInt16		GetRemotePort() { return ntohs(fRemoteAddr.sin_port); }
	//This function is NOT thread safe!
	std::string	GetRemoteAddrStr();
	
	void		ClearFD() { fFileDesc = kInvalidFileDesc; fState = 0;}

    protected:
        enum
        {
            kIPAddrBufSize = 20 //UInt32
        };

        struct sockaddr_in	fRemoteAddr;
	std::string		fRemoteStr;
};
#endif // __TCPSOCKET_H__

